package sketch.skeleton;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import sketch.generator.SequenceGenerator;
import sketch.util.Checker;

public class GeneratorMaps {

	private static int counter = 0;
	
	private static final Map<Integer, SequenceGenerator<?>> innerMaps = new LinkedHashMap<Integer, SequenceGenerator<?>>();
	
	public static void resetCounter() {
		counter = 0;
	}
	
	public static void resetGenerator() {
		for(SequenceGenerator<?> generator : innerMaps.values()) {
			generator.reset();
		}
	}
	
	public static void clear() {
		resetCounter();
		innerMaps.clear();
	}
	
	/**
	 * If the inner map contains a generator, the tool returns the existing one. or else
	 * update the map and return the newly added one.
	 * */
	public static SequenceGenerator<?> lookForGenerator(SequenceGenerator<?> generator) {
		Checker.checkNull(generator, "The generator parameter could not be null!");
		counter = counter + 1;
		//System.out.println("counter: " + counter);
		if(innerMaps.containsKey(counter)) {
			return innerMaps.get(counter);
		} else {
			innerMaps.put(counter, generator);
			return generator;
		}
	}
	
	/**
	 * Returns all sequence generator in the increasing order of key
	 * */
	public static List<SequenceGenerator<?>> collectGenerators() {
		List<SequenceGenerator<?>> retGenerators = new LinkedList<SequenceGenerator<?>>();
		//get the keys and sort them
		Integer[] keys = (Integer[]) innerMaps.keySet().toArray(new Integer[0]);
		Arrays.sort(keys);
		//fetch generators in order
		for(Integer key : keys) {
			SequenceGenerator<?> generator = innerMaps.get(key);
			retGenerators.add(generator);
		}
		return retGenerators;
	}
}
